﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CrossGenLogic;
using System.IO;

namespace CrossGenGUI
{
    public partial class Main : Form
    {
        private Form Options, Edit, DataInfo, About;
        private Generator Gen;
        private Field buttons = new Field();

        public Main()
        {
            InitializeComponent();
        }

        public bool CreateCross(string vocname, string gridname, int diff, bool isFill)
        {
            Gen = new Generator(vocname, gridname, diff);
            if (isFill)
            {
                if (Gen.Generate(Gen.GetFirstGE(), -1))
                {
                    textBox1.Text = Gen.GetQuestions();
                    PaintField(Gen.CrossHeigth(), Gen.CrossWidth(), Gen);
                    BFillWords.Visible = false;
                    return true;
                }
                else
                {
                    MessageBox.Show("Не удалось заполнить сетку словами");
                    return false;
                }
            }
            textBox1.Text = "";
            Gen.SetIndex();
            PaintField(Gen.CrossHeigth(), Gen.CrossWidth(), Gen);
            BFillWords.Visible = true;
            return true;
        }

        public bool CreateCross(string vocname, int count, int diff, bool isFill)
        {
            Gen = new Generator(vocname, count, diff);
            if (Gen.isGridGenerated())
            {
                if (isFill)
                {
                    if (Gen.Generate(Gen.GetFirstGE(), -1))
                    {
                        textBox1.Text = Gen.GetQuestions();
                        PaintField(Gen.CrossHeigth(), Gen.CrossWidth(), Gen);
                        BFillWords.Visible = false;
                        return true;
                    }
                    else
                    {
                        MessageBox.Show("Не удалось заполнить сетку словами");
                        return false;
                    }
                }
            }
            else
            {
                MessageBox.Show("Не удалось сгенерировать сетку");
                return false;
            }
            textBox1.Text = "";
            Gen.SetIndex();
            PaintField(Gen.CrossHeigth(), Gen.CrossWidth(), Gen);
            BFillWords.Visible = true;
            return true;
        }

        private void PaintField(int height, int width, Generator gener)
        {
            foreach (Button b in buttons)
            {
                this.Controls.Remove(b);
            }
            buttons = new Field(height, width, gener);
            foreach (Button b in buttons)
            {
                this.Controls.Add(b);
            }
        }

        private void создатьКроссвордToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "Options")
                {
                    return;
                }
            }
            Options = new Options(this);
            Options.Show();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (Gen.Generate(Gen.GetFirstGE(), -1))
            {
                textBox1.Text = Gen.GetQuestions();
                buttons.UpdateField(Gen);
                BFillWords.Visible = false;
            }
            else
            {
                MessageBox.Show("Не удалось заполнить сетку словами");
            }
        }

        private void загрузитьКроссвордToolStripMenuItem_Click(object sender, EventArgs e)
        {
            openFileDialog1.FileName = "";
            openFileDialog1.InitialDirectory = "Crosswords";
            openFileDialog1.Filter = "CrossGen files (*.cgg)|*.cgg|txt files (*.txt)|*.txt|All files (*.*)|*.*";
            openFileDialog1.FilterIndex = 1;
            openFileDialog1.RestoreDirectory = true;
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                CreateCross("Dictionaries\\general.cdic", openFileDialog1.FileName, 1, false);
            }
        }

        private void сохранитьКроссвордToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Gen != null && Gen.WordsCount() > 0)
            {
                saveFileDialog1.FileName = "Unnamed.cgg";
                saveFileDialog1.InitialDirectory = "Crosswords";
                saveFileDialog1.Filter = "CrossGen files (*.cgg)|*.cgg|txt files (*.txt)|*.txt|All files (*.*)|*.*";
                saveFileDialog1.FilterIndex = 1;
                saveFileDialog1.RestoreDirectory = true;
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        using (StreamWriter writeFile = new StreamWriter(saveFileDialog1.FileName, false, System.Text.Encoding.Default))
                        {
                            string linetowrite;
                            linetowrite = Gen.CrossWidth().ToString() + ", " + Gen.CrossHeigth().ToString();
                            writeFile.WriteLine(linetowrite);
                            for (int i = 0; i < Gen.WordsCount(); i++)
                            {
                                GridElement ge = Gen.GetGridElement(i);
                                linetowrite = ge.X.ToString() + ", " + ge.Y.ToString() + ", " + ge.Length.ToString() + ", ";
                                if (ge.dx() == 1) linetowrite += "h";
                                else linetowrite += "v";
                                writeFile.WriteLine(linetowrite);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Произошла ошибка при сохранении кроссворда. " + ex.Message);
                    }
                }
            }
            else MessageBox.Show("Кроссворд еще не создан");
        }

        private void выходToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void редактированиеToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "Edit")
                {
                    return;
                }
            }
            Edit = new Edit();
            Edit.Show();
        }

        private void структураДанныхToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "DataInfo")
                {
                    return;
                }
            }
            DataInfo = new DataInfo();
            DataInfo.Show();
        }

        private void оПрограммеToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "About")
                {
                    return;
                }
            }
            About = new About();
            About.Show();
        }


    }
}
